package com.cstz.ydshop.common.utils;

import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

/**
 * 将地址转换成经纬度
 */

@Slf4j
public class AddressUtils {

    public static Map<String,Object> getLngLat(String address){
        StringBuffer sb = new StringBuffer();
        Map<String,Object> map = Maps.newHashMap();
        try{
            URL url = new URL("http://restapi.amap.com/v3/geocode/geo?address="+address+"&output=JSON&key=7f4ffae4074e8b8e4d147190527a4b72");
            URLConnection yc = url.openConnection();
            //读取返回的数据
            BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(),"UTF-8"));
            String inputline = null;
            while((inputline=in.readLine())!=null){
                sb.append(inputline);
            }
            
            JSONObject jsonObject = JSONObject.fromObject(sb.toString());
            log.info("返回信息,{}",sb.toString());
            if(null!=jsonObject && jsonObject.containsKey("status") && jsonObject.containsKey("geocodes")
            && jsonObject.containsKey("info") && "1".equals(jsonObject.getString("status")) && "OK".equals(jsonObject.getString("info"))){
                if(jsonObject.getJSONArray("geocodes").size()>0){
                    String str = jsonObject.getJSONArray("geocodes").getJSONObject(0).getString("location");
                    if(StringUtils.isNotEmpty(str) && str.contains(",")){
                        map.put("lng",str.split(",")[0]);
                        map.put("lat",str.split(",")[1]);
                    }
                }
            }
            
        }catch (Exception e){
            log.error("地址转换成经纬度异常,{}",e.getMessage());
        }
       
        return map;
    }
}
